<template>
  <div class="container" :style="{'overflow': shareBannerShow ? 'hidden':'auto'}">
    <main-header :actived="4" />
    <!-- 用户信息 -->
    <div class="user-infor" @click="goToUserBase">
      <img v-if="userInfoDetail.Photo==='' || userInfoDetail.Photo===null" class="avatar" src='../../assets/img/person.png' />
      <img v-else class="avatar" :src='userInfoDetail.Photo' />
      <div class="infor">
        <h3>{{userInfoDetail.Nick}}</h3>
        <!-- <p>{{userInfoDetail.Email}}</p> -->
      </div>
      <div class="arrow"></div>
    </div>
    <!-- 用户订单 -->
    <div class="user-orders">
      <div class="tit" @click="goToOrders('')">
        <h3>我的订单</h3>
        <a class="more">查看全部</a>
      </div>
      <div class="con">
        <a class="item" @click="goToOrders(1)">
          <img src='../../assets/img/user-orders-1.png' />
          <span>待付款</span>
          <i v-if="orderStatusNum[0]">{{orderStatusNum[0]}}</i>
        </a>
        <a class="item" @click="goToOrders(2)">
          <img src='../../assets/img/user-orders-2.png' />
          <span>待发货</span>
          <i v-if="orderStatusNum[1]">{{orderStatusNum[1]}}</i>
        </a>
        <a class="item" @click="goToOrders(3)">
          <img src='../../assets/img/user-orders-3.png' />
          <span>待收货</span>
          <i v-if="orderStatusNum[2]">{{orderStatusNum[2]}}</i>
        </a>
        <a class="item" @click="goToOrders(4)">
          <img src='../../assets/img/user-orders-4.png' />
          <span>评价有礼</span>
          <i v-if="orderStatusNum[3]">{{orderStatusNum[3]}}</i>
        </a>
        <a class="item" @click="goToOrdersRefund">
          <img src='../../assets/img/user-orders-5.png' />
          <span>退货退款</span>
          <i v-if="refundOrders.length">{{refundOrders.length}}</i>
        </a>
      </div>
    </div>
    <!-- 导航链接 -->
    <div class="user-navs">
      <router-link to="/score" class="item item-mt">
        <div class="label">TA会员积分</div>
        <div class="value">{{userInfoDetail.Integral}}</div>
        <div class="arrow"></div>
      </router-link>
      <router-link to="/userClass" class="item">
        <div class="label">课程活动</div>
        <div class="value">{{classLenth}}</div>
        <div class="arrow"></div>
      </router-link>
      <router-link to="/myCoupon" class="item">
        <div class="label">优惠券</div>
        <div class="value">{{userCouponNum}}</div>
        <div class="arrow"></div>
      </router-link>
      <router-link to="/collection" class="item">
        <div class="label">收藏</div>
        <div class="value">{{collectionTotal}}</div>
        <div class="arrow"></div>
      </router-link>
      <router-link to="/history" class="item">
        <div class="label">浏览足迹</div>
        <div class="value">{{historyTotal}}</div>
        <div class="arrow"></div>
      </router-link>
      <!-- <router-link to="/notice" class="item">
        <div class="label">消息通知</div>
        <div class="value"><i class="new"></i></div>
        <div class="arrow"></div>
      </router-link> -->
      <router-link to="/address" class="item item-mt">
        <div class="label">收货地址</div>
        <div class="arrow"></div>
      </router-link>
      <!-- <router-link to="/ticket" class="item">
        <div class="label">发票管理</div>
        <div class="arrow"></div>
      </router-link> -->
      <!-- <router-link to="/payment" class="item">
        <div class="label">支付管理</div>
        <div class="arrow"></div>
      </router-link> -->
      <div class="item item-mt" v-if="canApply" @click="applyBelong">
        <div class="label">TITIKA未来城市主理人招募</div>
        <div class="arrow"></div>
      </div>
      <div class="item item-mt" v-if="isBelongMan" @click="belongMan">
        <div class="label">TITIKA签约城市主理人</div>
        <div class="arrow"></div>
      </div>

      <div class="item item-mt" v-if="userKey" @click="logout">
        <div class="label">退出登录</div>
        <div class="arrow"></div>
      </div>
    </div>
    <div class="share" @click="share">
      <img src="../../assets/img/logo-shape.png" />
      <div class="word">
        <p>分享</p>
        <p>领券</p>
      </div>
    </div>
    <!-- 分享展示层 -->
    <div class="share-banner" v-show="shareBannerShow">
      <div class="banner" id="shareDom">
        <!-- <img src="http://shop.jdpin.com.cn/Storage/template/0/20200519/6372547886359690266994727.jpg" /> -->
        <img src="../../assets/img/haibao.jpg" />
        <div class="qrcode" id="qrcode"></div>
      </div>
      <div id="shareRet">
        <van-loading 
          v-if="!shareImg" 
          class="share-loading" 
          size="24px" 
          vertical
        >
          海报生成中...
        </van-loading>
        <img v-if="shareImg" :src='shareImg' />
      </div>
      <div class="share-btns">
        <div class="item item-1" @touchstart.prevent="press">
          <div class="img"></div>
          <!-- <img src="../../assets/img/icon-hb.png" /> -->
          <h3>长按上图保存</h3>
        </div>
        <div class="item item-2" id="copyBtn">
          <div class="img"></div>
          <!-- <img src="../../assets/img/icon-link.png" /> -->
          <h3>复制链接</h3>
        </div>
      </div>
      <div class="close" @click="closeShare">&times;</div>
    </div>
  </div>
</template>

<script>
import MainHeader from 'components/content/MainHeader'
import { 
  getUserInfo, 
  getUserDetail, 
  getUserCollectionProduct,
  getUserCollectionArticle,
  getHistoryVisite,
  getUserOrders,
  getUserDetailById,
  logout
} from '../../network/user'
import { applyBelong } from '../../network/belong'

import { drawHtml, copyInit } from '../../utils/share'
import { multLogin } from '../../utils/wx'
import { getUserCoupon } from '../../network/coupon'
import { EVN, productionDomain, natDomain } from "../../config/global"
import { getRefundList } from '../../network/order'
import { getUserClass } from '../../network/user'

export default {
  name: 'User',
  components: {
    MainHeader,
  },
  data() {
    return {
      userKey: localStorage.getItem('userKey'),
      userInfo: {},
      userInfoDetail: {},
      canApply: false,
      isBelongMan: JSON.parse(localStorage.getItem('isBelongMan')),
      collectionTotal: 0,
      historyTotal: 0,
      shareBannerShow: false,
      shareImg: '',
      userCouponNum: 0,
      orderStatusNum: [0,0,0,0,0],
      refundOrders: [],
      classLenth: 0,
    }
  },
  // destroyed(){ 
  //   // 监听物理返回
  //   window.removeEventListener('popstate', this.goBack, false) 
  // },
  async mounted() {
    sessionStorage.setItem('need-refresh', true)
    // 监听物理返回
    // if(window.history && window.history.pushState){
    //   history.pushState(null, null, document.URL)
    //   window.addEventListener('popstate', this.goBack, false)
    // }
    
    // 用户登录
    let loginStatus = await multLogin(this)
    if(!loginStatus) return false

    this.getUserInfo()
    this.getUserDetail()
    this.getUserCollectionProduct()
    this.getUserCollectionArticle()
    this.getUserCoupon()
    this.getUserOrders()
    getHistoryVisite(res => {
      this.historyTotal = res.length
    })
    getRefundList(list => {
      // 获取退货退款中待订单数量
      this.refundOrders = list.filter(item => !(item.SellerAuditStatusValue === 5 && item.RefundStatus !=='待平台确认') )
    })
    // 获取课程数
    await this.getUserClass()
    copyInit()
  },
  methods: {
    press(e){},
    // async goBack(){ 
    //   // 监听物理返回
    //   this.$router.replace({path: '/user'})
    //   let loginStatus = await multLogin(this)
    // },
    async share(){
      this.shareBannerShow = true
      if(this.shareImg === ''){
        this.shareImg = await drawHtml(this, '#shareDom', '#shareRet')
      }
    },
    closeShare(){
      this.shareBannerShow = false
    },
    
    getUserInfo(){
      let requestData = {
        userkey: this.userKey
      }
      getUserInfo(requestData, info => {
        this.userInfo = info
      })
    },
    getUserDetail(){
      let requestData = {
        userkey: this.userKey
      }
      getUserDetail(requestData, async info => {
        this.userInfoDetail = info

        // 特殊通道，申请城市运营商后未填写表单
        // if(
        //   this.userInfoDetail.Nick === 'titikahzwzx' || 
        //   this.userInfoDetail.Nick === '13429331015' || 
        //   this.userInfoDetail.Nick === 'titika_YJyoga1'
        // ){
        //   this.$router.push({
        //     path: 'belongApply',
        //     query: {
        //       action: 'ISP'
        //     }
        //   })
        // }
        
        // 判断自己是否是城市运营商、主理人
        let userinfo = await this.getIsISPorBelong(info.UserId)
        // 判断是否是城市运营商
        let isISP = userinfo.IsISP
        let isBelongMan = userinfo.IsDistributor
        localStorage.setItem("isISP", isISP)
        localStorage.setItem("isBelongMan", isBelongMan)
        this.isBelongMan = userinfo.IsDistributor

        // 判断上级是否是运营商
        if(info.ParentMember===null){ // 不存在上级
          return false
        }
        let shareinfo = await this.getIsISPorBelong(info.ParentMember.Id)

        // canApply: 自己不是主理人 且 有上级并上级不是运营商
        // console.log(!userinfo.IsDistributor , info.ParentMember , !shareinfo.IsISP)
        this.canApply = !userinfo.IsDistributor && info.ParentMember && !shareinfo.IsISP
        
      })
    },
    getIsISPorBelong(userId) {
      return new Promise((resolve) => {
        getUserDetailById(userId, (userInfo) => {
          resolve(userInfo)
        })
      })
    },
    getUserCollectionProduct(){
      let requestData = {
        UserKey: this.userKey,
        pageNo: 1,
        pageSize: 200,
      }
      getUserCollectionProduct(requestData, res => {
        this.collectionTotal += res.total
      })
    },
    getUserCollectionArticle(){
      let requestData = {
        userkey: this.userKey,
      }
      getUserCollectionArticle(requestData, list => {
        this.collectionTotal += list.length
      })
    },
    getUserOrders(){
      return new Promise((resolve, reject) => {
        let requestData = {
          userKey: this.userKey,
          pageNo: 1,
          pageSize: 100,
          orderStatus: '',
        }
        getUserOrders(requestData, res => {
          res.Orders.map(item => {
            if(item.orderStatus === 1){
              let num = this.orderStatusNum[0] + 1
              this.$set(this.orderStatusNum, 0, num)
            }
            if(item.orderStatus === 2){
              let num = this.orderStatusNum[1] + 1
              this.$set(this.orderStatusNum, 1, num)
            }
            if(item.orderStatus === 3){
              let num = this.orderStatusNum[2] + 1
              this.$set(this.orderStatusNum, 2, num)
            }
            if(item.orderStatus === 5 && item.commentCount === 0){
              let num = this.orderStatusNum[3] + 1
              this.$set(this.orderStatusNum, 3, num)
            }
            return item
          })
          // this.$set(this.orderStatusNum, 0, res.WaitingForPay)
          // this.$set(this.orderStatusNum, 2, res.WaitingForRecieve)
          // this.$set(this.orderStatusNum, 3, res.WaitingForComments)
          resolve()
        })
      })
    },
    getUserClass(){
      return new Promise((resolve, reject) => {
        let requestData = {
          userKey: this.userKey,
          pageNo: 1,
          pageSize: 100,
          orderStatus: '',
        }
        getUserClass(requestData, res => {
          this.classLenth = res.Orders.length
          resolve()
        })
      })
    },
    goToOrders(statusIndex){
      this.$router.push({
        path: '/orders',
        query: {
          statusIndex
        }
      })
    },
    goToOrdersRefund(){
      this.$router.push({
        path: '/ordersRefund'
      })
    },
    getUserCoupon(){
      let requestData = {
        userkey: this.userKey
      }
      getUserCoupon(requestData, list => {
        this.userCouponNum = list.length
      })
    },
    goToUserBase(){
      this.$router.push('/userBase')
    },
    applyBelong(){
      this.$router.push('/belongApply')
    },
    belongMan(){
      this.$router.push('/belong')
    },
    logout(){
      logout()
    }
  },
}
</script>

<style scoped>
.container{
  height: 100vh;
  overflow: auto;
}
.user-infor{
  padding: 20px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #ffffff;
  background-color: #000000;
}
.user-infor img{
  width: 45px;
  height: 45px;
  border-radius: 50%;
  margin-right: 20px;
  border: 1px solid #ffffff;
}
.user-infor .infor{
  flex-grow: 1;
}
.user-infor .infor h3{
  font-size: 16px;
  padding-bottom: 6px;
}
.user-infor .infor p{
  font-size: 14px;
}
.user-infor .arrow{
  width: 6px;
  height: 6px;
  border-top: 2px solid #ffffff;
  border-right: 2px solid #ffffff;
  transform: rotate(45deg);
}
.user-orders{
  padding: 30px;
  background-color: #ffffff;
}
.user-orders .tit{
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #dddddd;
  padding-bottom: 10px;
}
.user-orders .tit h3{
  font-size: 14px;
}
.user-orders .tit a{
  position: relative;
  font-size: 14px;
  color: #8c8c8c;
  padding-right: 20px;
}
.user-orders .tit a:after{
  position: absolute;
  top: 6px;
  right: 10px;
  content: '';
  width: 6px;
  height: 6px;
  border-top: 1px solid #8c8c8c;
  border-right: 1px solid #8c8c8c;
  transform: rotate(45deg);
}
.user-orders .con{
  display: flex;
  margin: 0 -10px;
}
.user-orders .con .item{
  position: relative;
  width: 20%;
  height: 70px;
  font-size: 12px;
  text-align: center;
}
.user-orders .con .item img{
  display: block;
  margin: 20px auto 8px auto;
  width: 34px;
  height: 34px;
}
.user-orders .con .item i{
  display: block;
  position: absolute;
  top: 12px;
  right: 4px;
  color: #ffffff;
  border-radius: 20px;
  line-height: 20px;
  min-width: 10px;
  padding: 0 5px;
  background-color: #d50721;
}
.user-navs{
  padding-bottom: 10px;
}
.user-navs .item{
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  height: 50px;
  font-size: 14px;
  border-top: 1px solid #f7f7f7;
  background-color: #ffffff;
}
.user-navs .item-mt{
  margin-top: 10px;
  border-top: none;
}
.user-navs .item .value{
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-grow: 1;
  color: #8c8c8c;
  text-align: right;
}
.user-navs .item .value .new{
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background-color: #d50721;
}
.user-navs .item .arrow{
  width: 6px;
  height: 6px;
  border-top: 1px solid #8c8c8c;
  border-right: 1px solid #8c8c8c;
  transform: rotate(45deg);
  margin-left: 10px;
}
.share{
  position: fixed;
  right: 10px;
  bottom: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 102px;
  height: 50px;
  padding: 0 18px 2px 15px;
  box-sizing: border-box;
  border-radius: 40px;
  color: #ffffff;
  background-color: #000;
}
.share img{
  width: 30px;
}
.share .word{
  line-height: 1.2;
  font-size: 14px;
}
.share-banner{
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  box-sizing: border-box;
  padding: 20px;
  background-color: #fff;
  z-index: 10;
}
.share-banner .banner{
  position: relative;
  overflow: hidden;
}
.share-banner .banner img{
  width: 100%;
}
.share-banner .share-btns{
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 80px;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  z-index: 9;
}
.share-banner .share-btns .item{
  text-align: center;
  /* flex-grow: 1; */
  width: 50%;
}
.share-banner .share-btns .item .img{
  display: inline-block;
  width: 35px;
  height: 35px;
  margin-bottom: 5px;
  background: url(../../assets/img/icon-hb.png);
  background-size: 100% auto;
}
.share-banner .share-btns .item-2 .img{
  background: url(../../assets/img/icon-link.png);
  background-size: 100% auto;
}
.share-banner .qrcode{
  width: 64px;
  height: 64px;
  margin-left: -32px;
  background-color: #fff;
  position: absolute;
  bottom: 70px;
  left: 50%;
  padding: 5px;
  box-sizing: border-box;
  z-index: 2;
}
.share-banner #shareRet{
  /* display: none; */
  position: absolute;
  bottom: 80px;
  left: 20px;
  right: 20px;
  top: 20px;
  overflow: hidden;
  z-index: 20;
  background-color: #fff;
}
/* .share-banner #shareRet::-webkit-scrollbar {
  width: 0;
  height: 0;
  -webkit-overflow-scrolling: touch;
  -ms-overflow-style: none;
  overflow: -moz-scrollbars-none;
  background-color: rgba(240,240,240,0)
} */
.share-banner .share-loading{
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -20px 0 0 -40px;
}
.share-banner #shareRet img{
  width: 100%;
  vertical-align: baseline;
}
.close{
  position: absolute;
  top: 12px;
  right: 13px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  text-align: center;
  line-height: 22px;
  color: #fff;
  font-size: 20px;
  z-index: 21;
  background-color: #000;
}
</style>

<style>
.share-banner #shareRet canvas{
  margin-left: -900px;
}
</style>